package com.gxy.learn.backup.shiroauth.shiro.filter;

import com.alibaba.fastjson.JSONObject;
import com.gxy.learn.backup.shiroauth.common.CommonConsts;
import com.gxy.learn.backup.shiroauth.common.Result;
import com.gxy.learn.backup.shiroauth.common.exception.BusinessException;
import com.gxy.learn.backup.shiroauth.entity.SysMenu;
import com.gxy.learn.backup.shiroauth.service.SysMenuService;
import com.gxy.learn.backup.shiroauth.service.SysUserService;
import com.gxy.learn.backup.shiroauth.shiro.config.JwtToken;
import com.gxy.learn.backup.shiroauth.shiro.config.JwtVerifyTokenAuxiliary;
import com.gxy.learn.backup.shiroauth.shiro.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Description(jwt 过滤器 过滤所有需要验证的请求)
 * author: Gao xueyong
 * Create at: 2022/1/4 下午10:53
 */
@Slf4j
public class JwtAuthFilter extends BasicHttpAuthenticationFilter {

    private JwtVerifyTokenAuxiliary jwtVerifyTokenAuxiliary;
    private SysUserService sysUserService;
    private SysMenuService sysMenuService;

    public JwtAuthFilter(JwtVerifyTokenAuxiliary jwtVerifyTokenAuxiliary, SysUserService sysUserService, SysMenuService sysMenuService) {
        this.jwtVerifyTokenAuxiliary = jwtVerifyTokenAuxiliary;
        this.sysUserService = sysUserService;
        this.sysMenuService = sysMenuService;
    }

    /**
     * 判断是否需要登录 需要则进入登录方法 不需要则返回true
     *
     * @param request     ServletRequest
     * @param response    ServletResponse
     * @param mappedValue mappedValue
     * @return 是否成功
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException {
        if (!isLoginAttempt(request, response)) {
            response401(request, response, "请先登录！");
            return false;
        }
        //如果存在，则进入 executeLogin 方法执行登入，检查 token 是否正确(这里指用户名和密码)
        try {
            return executeLogin(request, response);
        } catch (Exception e) {
            this.sendChallenge(request, response);
            response401(request, response, e.getMessage());
            return false;
        }
    }


    /**
     * 重新 onAccessDenied 去除executeLogin 放置循环调用doGetAuthenticationInfo方法
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        this.sendChallenge(request, response);
        return false;
    }

    /**
     * 重写executeLogin 进行AccessToken登录认证授权
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        // 拿到当前Header中Authorization的AccessToken(Shiro中getAuthzHeader方法已经实现)
        JwtToken token = new JwtToken(this.getAuthzHeader(request));
        Subject subject = this.getSubject(request, response);
        // 提交给UserRealm进行认证，如果错误他会抛出异常并被捕获
        this.getSubject(request, response).login(token);
        // 如果没有抛出异常则代表登入成功，返回true
        return onLoginSuccess(token, subject, request, response);
    }


    /**
     * 检测header里是否包含token
     *
     * @param request
     * @param response
     * @return true 包含 false 不包含
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        String token = getAuthzHeader(request);
        return StringUtils.isNotBlank(token);
    }
//
//    /**
//     * 刷新token
//     * @param issueAt
//     * @return
//     */
//    protected boolean shouldTokenRefresh(Date issueAt){
//        LocalDateTime issueTime = LocalDateTime.ofInstant(issueAt.toInstant(), ZoneId.systemDefault());
//        return LocalDateTime.now().minusSeconds(JwtUtil.EXPIRE_TIME).isAfter(issueTime);
//    }

    @Override
    protected String getAuthzHeader(ServletRequest request) {
        HttpServletRequest httpRequest = WebUtils.toHttp(request);
        return httpRequest.getHeader("Authorization");
    }


    /**
     * 对跨域提供支持 拦截前进行执行
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 重写生成shiro生成token的方法
     *
     * @param servletRequest
     * @param servletResponse
     * @return
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) {
        String jwtToken = getAuthzHeader(servletRequest);
        if (StringUtils.isBlank(jwtToken) || JwtUtil.isTokenExpired(jwtToken)) {
            return null;
        }
        return new JwtToken(jwtToken);
    }

    /**
     * 登录成功！
     *
     * @param token
     * @param subject
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        // 验证权限
        log.info("登录成功！ 需要实现验证权限");
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String url = httpServletRequest.getRequestURI();
        if (StringUtils.equals(CommonConsts.OUT_URL, url)) {
            return Boolean.TRUE;
        }
        SysMenu sysMenu = sysMenuService.getSysMenuByHref(url);
        if (null == sysMenu) {
            log.error("未知的请求！");
            throw new BusinessException("未知的请求！");
        }
        boolean permitted = subject.isPermitted(sysMenu.getPermission());
        log.info("permitted = {}", permitted);
        if (!permitted) {
            log.error("暂无权限访问！");
            throw new BusinessException("未知的请求！");
        }
        log.info("权限验证通过！");
        return Boolean.TRUE;
    }

    /**
     * 无需转发，直接返回Response信息
     */
    private void response401(ServletRequest request, ServletResponse response, String msg) {
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        HttpServletRequest req = (HttpServletRequest) request;
        log.error("url:{},errorMsg:{}", req.getRequestURI(), msg);
        try (PrintWriter out = httpServletResponse.getWriter()) {
            out.append(JSONObject.toJSONString(Result.error("无权访问(Unauthorized):" + msg)));
        } catch (IOException e) {
            log.error("直接返回Response信息出现IOException异常:{}", e.getMessage());
            throw new BusinessException("直接返回Response信息出现IOException异常:" + e.getMessage());
        }
    }
}
